package org.road0329.dlt698.asn1.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class AxdrOctetString extends AxdrType {
    private static Logger logger = LoggerFactory.getLogger(AxdrOctetString.class);
    private byte[] octetString = null;
    private int length = 0;

    public AxdrOctetString() {
    }

    public byte[] getOctetString() {
        return octetString;
    }

    public int getLength() {
        return length;
    }

    public AxdrOctetString(int length) {
        this.length = length;
    }

    public void setLength(int length) {
        this.length = length;
        this.octetString = new byte[length];
    }

    public void setDataCode(byte[] octetString) {
        if (octetString != null) {
            this.octetString = octetString;
        }
    }

    public void setAll(int length, byte[] octetString) {
        if (length != 0 && length != octetString.length) {
            throw new IllegalArgumentException("octetString of wrong size");
        }
        this.length = length;
        this.octetString = octetString;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        int len = this.length;
        if (len == 0) {
            AxdrLength l = new AxdrLength(0);
            codeLength += l.decode(input);
            len = l.getValue();
            this.octetString = new byte[len];
        }
        if (len != 0) {
            try {
                if (input.read(this.octetString, 0, len) < len) {
                    throw new Exception("Error Decoding AxdrOctetString");
                }
            } catch (IOException e) {
                logger.info("Error Decoding AxdrOctetString.", e);
                throw new Exception("Error Decoding AxdrOctetString");
            }
            codeLength += len;
        }
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.octetString != null) {
            output.writeByte(this.octetString);
            codeLength = this.octetString.length;
            if (this.length == 0) {
                AxdrLength length = new AxdrLength(this.octetString.length);
                codeLength += length.encode(output);
            }
        }
        return codeLength;
    }

    public byte[] getValue() {
        return this.octetString;
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        for (byte b : this.octetString) {
            String hexString = Integer.toHexString(b & 0xff);
            if (hexString.length() == 1) {
                s.append('0');
            }
            s.append(hexString);
        }
        return s.toString();
    }
}



